package com.dsdl.chatapp.module.chat;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dsdl.chatapp.R;
import com.dsdl.chatapp.contacts.Constant;
import com.dsdl.chatapp.data.SocketMessage;
import com.dsdl.chatapp.data.source.local.ChatPersistenceContract;
import com.dsdl.chatapp.common.db.ChatDAO;
import com.dsdl.chatapp.module.chat.adapter.ChatAdapter;
import com.dsdl.chatapp.common.utils.LogUtil;
import com.dsdl.chatapp.common.utils.SPUtil;
import com.dsdl.chatapp.common.utils.socket.ISocketManager;
import com.dsdl.chatapp.common.utils.socket.NewSocketManager;
import com.dsdl.chatapp.common.utils.socket.SocketPacket;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zzg on 2016/9/5.
 */
public class ChatFragment extends Fragment implements View.OnClickListener{
    private static String TAG = ChatFragment.class.getSimpleName();
    private ListView mListView;
    private EditText etInputContent;
    private TextView tvSend;

    private String mToPhone;

    private ChatAdapter mChatAdapter;
    private List<SocketMessage> mList = new ArrayList<>();

    private MessageReceiver mMessageReceiver;

    public static ChatFragment newInstance() {
        return new ChatFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMessageReceiver = new MessageReceiver();
        getActivity().registerReceiver(mMessageReceiver, new IntentFilter(Constant.CHAT_WINDOW_FILTER));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_chat, container, false);
        initView(root);
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mToPhone = getArguments().getString("phone");
        setData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMessageReceiver != null) {
            getActivity().unregisterReceiver(mMessageReceiver);
        }

    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.lv_chat_content);
        etInputContent = (EditText) view.findViewById(R.id.et_send_input);
        tvSend = (TextView) view.findViewById(R.id.tv_send);
        tvSend.setOnClickListener(this);

        mChatAdapter = new ChatAdapter(getActivity(), mList);
        mListView.setAdapter(mChatAdapter);
    }

    private void setData() {
        if (mToPhone == null){
            return;
        }
        List<SocketMessage> list = ChatDAO.getInstance().queryAll(ChatPersistenceContract.ChatEntry.COLUMN_NAME_FROM_USER+" = ? OR "+ChatPersistenceContract.ChatEntry.COLUMN_NAME_TO_USER+" = ?",new String[]{mToPhone,mToPhone},null);
        if (list != null){
            mList.addAll(list);
        }
        mChatAdapter.notifyDataSetChanged();
        if (mList.size() >0){
            mListView.smoothScrollToPosition(mList.size() - 1);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send:
                sendContentMessage();
                break;
            default:
                break;
        }
    }

    private void sendContentMessage() {
        SocketPacket packet = new SocketPacket();
        String message = etInputContent.getText().toString();
        if (TextUtils.isEmpty(message)) {
            Toast.makeText(getActivity(), "消息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        final SocketMessage socketMessage = new SocketMessage();
        socketMessage.setFromUser(SPUtil.getSharedStringData(Constant.USER_PHONE));
        socketMessage.setToUser(mToPhone);
        socketMessage.setContent(message);
        socketMessage.setMsgType("text");
        socketMessage.setCreateTime(System.currentTimeMillis());
        packet.setData(socketMessage);
        mList.add(socketMessage);
        mChatAdapter.notifyDataSetChanged();
        mListView.smoothScrollToPosition(mList.size() - 1);
        etInputContent.setText("");
        NewSocketManager.getInstance().sendMessage(packet, new ISocketManager.SendCallBack() {
            @Override
            public void begin() {

            }

            @Override
            public void success(SocketPacket sendPacket) {
                ContentValues values = new ContentValues();
                values.put(ChatPersistenceContract.ChatEntry.COLUMN_NAME_FROM_USER,socketMessage.getFromUser());
                values.put(ChatPersistenceContract.ChatEntry.COLUMN_NAME_TO_USER,socketMessage.getToUser());
                values.put(ChatPersistenceContract.ChatEntry.COLUMN_NAME_CREATE_TIME,socketMessage.getCreateTime());
                values.put(ChatPersistenceContract.ChatEntry.COLUMN_NAME_CONTENT,socketMessage.getContent());
                values.put(ChatPersistenceContract.ChatEntry.COLUMN_NAME_MSG_TYPE,socketMessage.getMsgType());
                long count = ChatDAO.getInstance().insert(values);
                LogUtil.d(TAG,count+"");
            }

            @Override
            public void error(String errorMsg) {

            }
        });
    }

    class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            SocketMessage chatMsg = intent.getParcelableExtra("chat_message");
            try {
                if (mList == null) {
                    mList = new ArrayList<>();
                }
                if (!"system".equals(chatMsg.getMsgType())) {
                    mList.add(chatMsg);
                    mChatAdapter.notifyDataSetChanged();
                    mListView.smoothScrollToPosition(mList.size() - 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
